package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.project.domain.CheckRecord;
import net.hn.hnms.biz.project.domain.ProjectInfo;
import net.hn.hnms.biz.project.domain.QualityControlFile;
import net.hn.hnms.biz.project.enums.QualityFileType;
import net.hn.hnms.biz.project.mapper.CheckRecordMapper;
import net.hn.hnms.biz.project.mapper.ProjectFileMapper;
import net.hn.hnms.biz.project.mapper.ProjectInfoMapper;
import net.hn.hnms.biz.project.mapper.QualityControlFileMapper;
import net.hn.hnms.biz.project.request.CheckRecordReq;
import net.hn.hnms.biz.project.service.ICheckRecordService;
import net.hn.hnms.biz.project.vo.CheckRecordVo;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘昊
 * @date 2024-03-12 14:48
 * 检查记录 service
 */
@Service
@Slf4j
public class CheckRecordServiceImpl implements ICheckRecordService {

    @Autowired
    private CheckRecordMapper checkRecordMapper;

    @Autowired
    private QualityControlFileMapper qualityControlFileMapper;

    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private ProjectFileMapper projectFileMapper;
    @Override
    public R<Void> insertReq(CheckRecordReq req) {

        CheckRecord CheckRecord = new CheckRecord();
        QualityControlFile QualityControlFile = new QualityControlFile();
        QueryWrapper<ProjectInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",req.getProjectId());
        //先查询项目信息（项目名称和施工单位）
        ProjectInfo projectInfo = projectInfoMapper.selectById(req.getProjectId());
        if (ObjectUtils.isEmpty(projectInfo)) {
            return R.fail("检查项目信息是否存在");
        }
        try {
            BeanUtils.copyProperties(req, CheckRecord);
            BeanUtils.copyProperties(req, QualityControlFile);
//            CheckRecord.setProjectName(projectInfo.getProjectName());
            log.info("检查记录新增========>");
            checkRecordMapper.insert(CheckRecord);
            QualityControlFile.setFileType(QualityFileType.TYPE_1.getValue());
            QualityControlFile.setRelevanceId(CheckRecord.getCheckRecordId());
            log.info("检查记录附件新增========>");
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("新增检查记录失败");
        }
        return R.ok("新增成功");
    }

    @Override
    public R<Void> deleteReq(CheckRecordReq req) {
        return null;
    }

    @Override
    public R<Void> updateReq(CheckRecordReq req) {

        CheckRecord CheckRecord = new CheckRecord();
        QualityControlFile QualityControlFile = new QualityControlFile();
        try {
            BeanUtils.copyProperties(req,CheckRecord);
            BeanUtils.copyProperties(req,QualityControlFile);
            checkRecordMapper.updateById(CheckRecord);
            QualityControlFile.setFileType(QualityFileType.TYPE_1.getValue());
            QualityControlFile.setRelevanceId(CheckRecord.getCheckRecordId());
            qualityControlFileMapper.insert(QualityControlFile);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("修改检查记录失败");
        }
        return R.ok("修改成功");
    }

    @Override
    public R<List<CheckRecordVo>> selectList(CheckRecordReq req) {

//        //先查询项目信息（项目名称和施工单位）
//        List<ProjectInfoVo> ProjectInfoList = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
//        // 提取projectId列表
//        List<String> projectIds = ProjectInfoList.stream()
//                .map(ProjectInfoVo::getProjectId)
//                .collect(Collectors.toList());
//
//        LambdaQueryWrapper<CheckRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper<QualityControlFile> qualityControlFileQuerywrapper = new QueryWrapper<>();
        List<CheckRecordVo> checkRecordVoList = new ArrayList<>();
//
//        recordQueryWrapper.in(CollectionUtils.isNotEmpty(projectIds),CheckRecord::getProjectId,projectIds)
//                .eq(StringUtils.isNotBlank(req.getProjectName()),CheckRecord::getProjectName,req.getProjectName())
//                .eq(StringUtils.isNotBlank(req.getConstructionUnit()),CheckRecord::getConstructionUnit,req.getConstructionUnit());


        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
        //提取projectId列表
        List<String> projectIds = projectListByCondition.stream()
                .map(ProjectInfoVo::getProjectId)
                .collect(Collectors.toList());
        req.setProjectIds(projectIds);


        List<CheckRecord> resList = checkRecordMapper.selectList(buildQuery(req));

        if (CollectionUtils.isNotEmpty(resList)) {
            for (CheckRecord CheckRecord : resList) {
                CheckRecordVo res = new CheckRecordVo();
                BeanUtils.copyProperties(CheckRecord,res);
                qualityControlFileQuerywrapper.eq("file_type",QualityFileType.TYPE_1.getValue());
                if(StringUtils.isNotBlank(CheckRecord.getCheckRecordId())) {
                    qualityControlFileQuerywrapper.eq("relevance_id",CheckRecord.getCheckRecordId());
                }
                List<QualityControlFile> fileDOList = qualityControlFileMapper.selectList(qualityControlFileQuerywrapper);
                res.setQualityControlFileList(fileDOList);
                checkRecordVoList.add(res);
            }
        }

        return R.ok("查询完成",checkRecordVoList);
    }

    @Override
    public R<Void> deleteList(List<String> idList) {
        try {
            checkRecordMapper.deleteBatchIds(idList);
//            idList.forEach(item -> {
//                checkRecordMapper.deleteById(item);
//            });
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    @Override
    public R<ResponsePage<List<CheckRecordVo>>> selectPageList(CheckRecordReq req, PageQuery pageQuery) {

//        //先查询项目信息（项目名称和施工单位）
//        List<ProjectInfoVo> ProjectInfoList = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
//        // 提取projectId列表
//        List<String> projectIds = ProjectInfoList.stream()
//                .map(ProjectInfoVo::getProjectId)
//                .collect(Collectors.toList());
//
//        LambdaQueryWrapper<CheckRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
//
//        recordQueryWrapper.eq(StringUtils.isNotBlank(req.getProjectId()),CheckRecord::getProjectId,req.getProjectId())
//                .eq(StringUtils.isNotBlank(req.getProjectName()),CheckRecord::getProjectName,req.getProjectName())
//                .eq(StringUtils.isNotBlank(req.getConstructionUnit()),CheckRecord::getConstructionUnit,req.getConstructionUnit())
//                .eq(StringUtils.isNotBlank(req.getMineCode()),CheckRecord::getMineCode,req.getMineCode());
//
        QueryWrapper<QualityControlFile> qualityControlFileQuerywrapper = new QueryWrapper<>();
        List<CheckRecordVo> checkRecordVoList = new ArrayList<>();
//
//        Page<CheckRecord> page = checkRecordMapper.selectPage(pageQuery.build(),recordQueryWrapper);


        //先查询项目信息（项目名称和施工单位）
        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition(req.getProjectId(), req.getConstructionUnit());
        if (Func.isNotEmpty(projectListByCondition)) {
            //提取projectId列表
            List<String> projectIds = projectListByCondition.stream()
                    .map(ProjectInfoVo::getProjectId)
                    .collect(Collectors.toList());
            req.setProjectIds(projectIds);

            Page<CheckRecord> page = checkRecordMapper.selectPage(pageQuery.build(), buildQuery(req).orderByDesc(CheckRecord::getCreateTime));

            List<CheckRecordVo> list = page.getRecords().stream().map(o -> {
                CheckRecordVo vo = new CheckRecordVo();
                BeanUtil.copyProperties(o, vo);

                // 获取项目名称和施工单位信息
                Optional<ProjectInfoVo> projectInfo = projectListByCondition.stream()
                        .filter(p -> p.getProjectId().equals(o.getProjectId()))
                        .findFirst();

                projectInfo.ifPresent(p -> {
                    vo.setProjectId(p.getProjectId());
                    vo.setProjectName(p.getProjectName());
                    vo.setConstructionUnit(p.getConstructionUnit());
                });

                return vo;
            }).collect(Collectors.toList());


            if (CollectionUtils.isNotEmpty(list)) {
                for (CheckRecordVo CheckRecord : list) {
                    CheckRecordVo res = new CheckRecordVo();
                    BeanUtils.copyProperties(CheckRecord,res);
                    qualityControlFileQuerywrapper.eq("file_type",QualityFileType.TYPE_1.getValue());
                    if(StringUtils.isNotBlank(CheckRecord.getCheckRecordId())) {
                        qualityControlFileQuerywrapper.eq("relevance_id",CheckRecord.getCheckRecordId());
                    }
                    List<QualityControlFile> fileDOList = qualityControlFileMapper.selectList(qualityControlFileQuerywrapper);
                    res.setQualityControlFileList(fileDOList);
                    checkRecordVoList.add(res);
                }
            }
            ResponsePage<List<CheckRecordVo>> resultPage = new ResponsePage<>(checkRecordVoList,page.getTotal());
            return R.ok("查询完成",resultPage);
        }else{
            ResponsePage<List<CheckRecordVo>> resultPage = new ResponsePage<>(projectListByCondition,0);
            return R.ok("查询完成",resultPage);
        }

    }


    private LambdaQueryWrapper<CheckRecord> buildQuery(CheckRecordReq req){
        return new LambdaQueryWrapper<CheckRecord>()
//                .like(StrUtil.isNotBlank(req.getVehicleCode()), CheckRecord::getVehicleCode, req.getVehicleCode())
                .in(!org.springframework.util.CollectionUtils.isEmpty(req.getProjectIds()), CheckRecord::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getProjectId()), CheckRecord::getProjectId, req.getProjectId())
                .eq(StrUtil.isNotBlank(req.getMineCode()), CheckRecord::getMineCode, req.getMineCode());
    }
}
